package com.xiang.ad.index.creative;

import com.xiang.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xiang.
 * 创意 index的服务
 */
@Slf4j
@Component
public class CreativeIndex implements IndexAware<Long, CreativeObject> {

    //id-CreativeObject
    private static Map<Long, CreativeObject> objectMap; //正向索引

    //使用线程安全的ConcurrentHashMap初始化map
    static {
        objectMap = new ConcurrentHashMap<>();
    }


    /**
     * 通过推广单元获取关联的创意实现
     * 创意与推广单元存在着多对多的关系
     * 1、可以通过creativeUnitIndex索引服务以及creativeUnitObject去获取到推广单元所有关联的创意的id
     * 2、再通过creativeIndex通过id再获取到对应的CreativeObject
     *
     * 这里实现第二步
     */
    public List<CreativeObject> fetch(Collection<Long> adIds) {

        //非空校验
        if (CollectionUtils.isEmpty(adIds)) {
            return Collections.emptyList();
        }

        //CreativeObject的返回对象，返回给索引服务用的
        List<CreativeObject> result = new ArrayList<>();

        //遍历，通过id获取CreativeObject
        adIds.forEach(u -> {
            CreativeObject object = get(u);
            if (null == object) {
                log.error("CreativeObject not found: {}", u);
                return;
            }

            result.add(object);
        });

        return result;
    }



    //通过id获取CreativeObject
    @Override
    public CreativeObject get(Long key) {
        return objectMap.get(key);
    }

    //添加索引
    @Override
    public void add(Long key, CreativeObject value) {

        log.info("before add: {}", objectMap);
        objectMap.put(key, value);
        log.info("after add: {}", objectMap);//打印日志用于对比结果
    }

    //更新索引
    @Override
    public void update(Long key, CreativeObject value) {

        log.info("before update: {}", objectMap);

        CreativeObject oldObject = objectMap.get(key);
        if (null == oldObject) {//如果oldObject为空，就add
            objectMap.put(key, value);
        } else {
            oldObject.update(value);//非空就update
        }

        log.info("after update: {}", objectMap);//打印日志，用于对比
    }

    //删除索引
    @Override
    public void delete(Long key, CreativeObject value) {

        log.info("before delete: {}", objectMap);
        objectMap.remove(key);
        log.info("after delete: {}", objectMap);//打印日志，用于比较结果
    }
}
